<template>
  <view class="login-container">
    <!-- 背景图 -->
    <image class="login-bg" src="https://ai-public.mastergo.com/ai/img_res/165c6f77412b962d593c294f033463f9.jpg" mode="aspectFill" />
    <view class="login-overlay"></view>
    
    <!-- 登录内容 -->
    <view class="login-content">
      <!-- 应用Logo和标题 -->
      <view class="login-header">
        <image class="login-logo" src="/static/logo.jpeg" mode="aspectFit" />
        <text class="login-title">哈喽音乐</text>
        <text class="login-subtitle">发现好音乐，享受好时光</text>
      </view>
      
      <!-- 登录表单 -->
      <view class="login-form">
        <!-- 用户名密码登录 -->
        <view class="form-group">
          <input 
            class="form-input" 
            v-model="loginForm.username"
            placeholder="请输入用户名" 
            placeholder-class="form-placeholder"
          />
        </view>
        <view class="form-group">
          <input 
            class="form-input" 
            v-model="loginForm.password"
            placeholder="请输入密码" 
            placeholder-class="form-placeholder"
            password
          />
        </view>
        
        <!-- 用户名密码登录按钮 -->
        <button class="login-btn username-login" @tap="handleUsernameLogin">
          <text class="login-text">登录</text>
        </button>
        
        <!-- 注册按钮 -->
        <button class="login-btn register-btn" @tap="handleRegister">
          <text class="login-text">注册新账号</text>
        </button>
        
        <!-- 微信一键登录 -->
        <button class="login-btn wechat-login" @tap="handleWechatLogin">
          <text class="login-icon">💚</text>
          <text class="login-text">微信一键登录</text>
        </button>
        
        <!-- 游客登录 -->
        <view class="guest-login" @tap="handleGuestLogin">
          <text class="guest-text">游客体验</text>
        </view>
      </view>
      
      <!-- 服务协议 -->
      <view class="agreement">
        <text class="agreement-text">登录即代表您同意</text>
        <text class="agreement-link">《用户协议》</text>
        <text class="agreement-text">和</text>
        <text class="agreement-link">《隐私政策》</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      isLogging: false,
      loginForm: {
        username: '',
        password: ''
      }
    }
  },
  methods: {
    // 微信登录
    async handleWechatLogin() {
      if (this.isLogging) return
      
      this.isLogging = true
      uni.showLoading({
        title: '登录中...'
      })
      
      try {
        // 调用微信登录接口
        const loginRes = await uni.login({
          provider: 'weixin'
        })
        
        if (loginRes.code) {
          // 发送code到后端服务器进行登录
          const response = await uni.request({
            url: 'http://localhost:3000/users/wechat-login',
            method: 'POST',
            data: {
              code: loginRes.code
            }
          })
          
          if (response.data.success) {
            this.loginSuccess({
              userId: response.data.data.userInfo.id,
              nickname: response.data.data.userInfo.username,
              avatar: response.data.data.userInfo.avatar || '/static/logo.png',
              token: response.data.data.token,
              loginType: 'wechat'
            })
          } else {
            throw new Error(response.data.error || '登录失败')
          }
        } else {
          throw new Error('获取微信授权码失败')
        }
      } catch (error) {
        console.error('微信登录失败:', error)
        uni.showToast({
          title: error.message || '登录失败，请重试',
          icon: 'none'
        })
      } finally {
        this.isLogging = false
        uni.hideLoading()
      }
    },
    
    // 用户名密码登录（虚拟账号）
    async handleUsernameLogin() {
      if (this.isLogging) return
      
      if (!this.loginForm.username || !this.loginForm.password) {
        uni.showToast({
          title: '请输入用户名和密码',
          icon: 'none'
        })
        return
      }
      
      this.isLogging = true
      uni.showLoading({
        title: '登录中...'
      })
      
      try {
        // 模拟登录延迟
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        // 虚拟账号验证
        const mockUsers = {
          'admin': '123456',
          'testuser': '123456',
          'demo': 'demo123',
          'user': 'password'
        }
        
        if (mockUsers[this.loginForm.username] === this.loginForm.password) {
          // 登录成功
          this.loginSuccess({
            userId: Date.now(),
            nickname: this.loginForm.username,
            avatar: '/static/logo.png',
            email: this.loginForm.username + '@example.com',
            token: 'mock_token_' + Date.now(),
            loginType: 'username'
          })
        } else {
          throw new Error('用户名或密码错误')
        }
      } catch (error) {
        console.error('登录失败:', error)
        uni.showToast({
          title: error.message || '登录失败，请重试',
          icon: 'none'
        })
      } finally {
        this.isLogging = false
        uni.hideLoading()
      }
    },
    
    // 注册新账号（虚拟注册）
    async handleRegister() {
      if (this.isLogging) return
      
      if (!this.loginForm.username || !this.loginForm.password) {
        uni.showToast({
          title: '请输入用户名和密码',
          icon: 'none'
        })
        return
      }
      
      this.isLogging = true
      uni.showLoading({
        title: '注册中...'
      })
      
      try {
        // 模拟注册延迟
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        // 虚拟注册验证
        const existingUsers = ['admin', 'testuser', 'demo', 'user']
        
        if (existingUsers.includes(this.loginForm.username)) {
          throw new Error('用户名已存在')
        }
        
        if (this.loginForm.username.length < 3) {
          throw new Error('用户名至少3个字符')
        }
        
        if (this.loginForm.password.length < 6) {
          throw new Error('密码至少6个字符')
        }
        
        // 注册成功
        uni.showToast({
          title: '注册成功，正在登录...',
          icon: 'success'
        })
        
        // 注册成功后自动登录
        setTimeout(() => {
          this.loginSuccess({
            userId: Date.now(),
            nickname: this.loginForm.username,
            avatar: '/static/logo.png',
            email: this.loginForm.username + '@example.com',
            token: 'mock_token_' + Date.now(),
            loginType: 'username'
          })
        }, 1000)
        
      } catch (error) {
        console.error('注册失败:', error)
        uni.showToast({
          title: error.message || '注册失败，请重试',
          icon: 'none'
        })
      } finally {
        this.isLogging = false
        uni.hideLoading()
      }
    },
    
    // 手机号登录
    async handlePhoneLogin() {
      if (this.isLogging) return
      
      this.isLogging = true
      uni.showLoading({
        title: '获取手机号...'
      })
      
      try {
        // 获取手机号授权
        const res = await uni.getUserProfile({
          desc: '用于完善会员资料'
        })
        
        // 模拟手机号登录成功
        setTimeout(() => {
          this.loginSuccess({
            userId: 'user_' + Date.now(),
            nickname: res.userInfo.nickName || '手机用户',
            avatar: res.userInfo.avatarUrl || '/static/logo.png',
            phone: '138****8888',
            loginType: 'phone'
          })
        }, 1000)
      } catch (error) {
        console.error('手机号登录失败:', error)
        uni.showToast({
          title: '登录失败，请重试',
          icon: 'none'
        })
      } finally {
        this.isLogging = false
        uni.hideLoading()
      }
    },
    
    // 游客登录
    handleGuestLogin() {
      this.loginSuccess({
        userId: 'guest_' + Date.now(),
        nickname: '游客',
        avatar: '/static/logo.png',
        phone: '',
        loginType: 'guest'
      })
    },
    
    // 登录成功处理
    loginSuccess(userInfo) {
      // 保存用户信息到本地存储
      uni.setStorageSync('userInfo', userInfo)
      uni.setStorageSync('isLogin', true)
      
      // 如果有token，也保存token
      if (userInfo.token) {
        uni.setStorageSync('token', userInfo.token)
      }
      
      uni.showToast({
        title: '登录成功',
        icon: 'success'
      })
      
      // 跳转到首页
      setTimeout(() => {
        uni.reLaunch({
          url: '/pages/home/home'
        })
      }, 1500)
    }
  }
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  position: relative;
}

.login-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.login-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(74, 107, 74, 0.3);
}

.login-content {
  position: relative;
  z-index: 1;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 120rpx 64rpx 80rpx;
}

.login-header {
  text-align: center;
  margin-bottom: 120rpx;
}

.login-logo {
  width: 120rpx;
  height: 120rpx;
  border-radius: 24rpx;
  margin-bottom: 32rpx;
}

.login-title {
  display: block;
  font-size: 48rpx;
  font-weight: 600;
  color: #ffffff;
  margin-bottom: 16rpx;
}

.login-subtitle {
  display: block;
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.8);
}

.login-form {
  display: flex;
  flex-direction: column;
  gap: 32rpx;
}

.form-group {
  margin-bottom: 24rpx;
}

.form-input {
  width: 100%;
  height: 88rpx;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 44rpx;
  padding: 0 32rpx;
  font-size: 28rpx;
  color: #4a6b4a;
  border: 2rpx solid rgba(107, 142, 107, 0.3);
  backdrop-filter: blur(10px);
}

.form-input:focus {
  border-color: #6b8e6b;
  background: rgba(255, 255, 255, 1);
}

.form-placeholder {
  color: #6b8e6b;
  font-size: 28rpx;
}

.login-btn {
  height: 96rpx;
  border-radius: 48rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  font-weight: 500;
}

.wechat-login {
  background: linear-gradient(135deg, #6b8e6b 0%, #4a6b4a 100%);
  color: #ffffff;
  box-shadow: 0 4rpx 16rpx rgba(74, 107, 74, 0.3);
}

.username-login {
  background: linear-gradient(135deg, #4a6b4a 0%, #6b8e6b 100%);
  color: #ffffff;
  box-shadow: 0 4rpx 16rpx rgba(74, 107, 74, 0.3);
}

.register-btn {
  background: rgba(255, 255, 255, 0.9);
  color: #4a6b4a;
  box-shadow: 0 4rpx 16rpx rgba(255, 255, 255, 0.3);
  backdrop-filter: blur(10px);
}

.phone-login {
  background: rgba(255, 255, 255, 0.9);
  color: #4a6b4a;
  box-shadow: 0 4rpx 16rpx rgba(255, 255, 255, 0.3);
  backdrop-filter: blur(10px);
}

.login-icon {
  font-size: 40rpx;
  margin-right: 16rpx;
}

.login-text {
  font-size: 32rpx;
}

.guest-login {
  text-align: center;
  padding: 32rpx;
}

.guest-text {
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.8);
  text-decoration: underline;
}

.agreement {
  text-align: center;
  margin-top: 40rpx;
}

.agreement-text {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.6);
}

.agreement-link {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.8);
  text-decoration: underline;
}
</style>